package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SercurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenManagerProperties jwt;

    @Autowired
    private SercurityConfigProperties sercurity;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public UserVo login(LoginDto loginDto) {

        User user = userMapper.selectByName(loginDto.getUsername());

        //用户未创建
        if(user == null){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        //用户被禁用
        if(user.getDataState().equals(SuperConstant.DATA_STATE_1)){
            throw new BaseException(BasicEnum.ACCOUNT_IS_FORBIDDEN);
        }

        //用户已注销
        if(user.getIsDelete() == SuperConstant.IS_DELETE_1){
            throw new BaseException(BasicEnum.ACCOUNT_IS_DELETE);
        }

        //用户名或密码错误
        if(!BCrypt.checkpw(loginDto.getPassword(),user.getPassword())){
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }

        Map map = new HashMap();
        map.put(Constants.JWT_USERID,user.getId());

        //获取白名单资源列表,加入urls列表中
        List<String> publicAccessUrls = sercurity.getPublicAccessUrls();
        Set<String> urls = new HashSet<>();
        urls.addAll(publicAccessUrls);

        //获取用户的资源列表
        List<String> userUrls = resourceMapper.selectUrlListByUserId(user.getId());
        urls.addAll(userUrls);


        String token = JwtUtil.createJWT("$2a$10$PVtHnkj86mJgf6li/yron.LRx/cQAlaiZkBJ9BeogCNTryXJRT1YC", 3600000, map);

        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        userVo.setPassword("");
        userVo.setUserToken(token);


        //将urls转成json字符串
        String jUrls = JSONUtil.toJsonStr(urls);

        //将url数据封装进redis缓存中
        redisTemplate.opsForValue().set(UserCacheConstant.USER_RESOURCE_LIST+user.getId(),jUrls,jwt.getTtl()/1000, TimeUnit.SECONDS);


        return userVo;
    }
}
